package ua.com.jpy.controllers.login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ua.com.jpy.entity.customer.Customer;
import ua.com.jpy.services.customer.ICustomerService;

/**
 * @author LSD25
 *
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
	
	private static final Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private ICustomerService customerService;
	
	@SuppressWarnings("deprecation")
	@RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
	public String login(ModelMap modelMap, @RequestParam(value = "loginError", required = false) String loginError) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Customer customer = null;
		if(authentication != null) {
			Object principial = authentication.getPrincipal();
			if(principial instanceof Customer) {
				customer = (Customer) authentication.getPrincipal();
				modelMap.addAttribute(customer);
			} else {
				String rolesCustomer = customerService.getStringCustomerRoles();
				log.info("Customer wit role: " + rolesCustomer);
			}
		}
		modelMap.addObject("errorMessage", loginError);
		log.info("Auth failed");
		return "test";
	}
	
}
